using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// Unity帮助脚本
/// 功能：提供一些常用功能方法，方便快速开发
/// </summary>
public class UnityHelper : MonoBehaviour
{

    /// <summary>
    /// 查找子对象
    /// </summary>
    /// <param name="goParent">父对象</param>
    /// <param name="childName">查找的子对象名称</param>
    /// <returns></returns>
    public static Transform FindTheChildNode(GameObject goParent, string childName)
    {
        Transform searchTransform = null;
        
        searchTransform = goParent.transform.Find(childName); //第一层搜索
        
        if (searchTransform == null)
        {
            foreach (Transform child in goParent.transform)
            {
                searchTransform = FindTheChildNode(child.gameObject,childName);
                if (searchTransform == null)
                {
                    continue;
                }
                return searchTransform;
            }
        }
        return searchTransform; //第一层输出
    }
    
    /// <summary>
    /// 获取子节点对象脚本
    /// </summary>
    /// <param name="goParent">父对象</param>
    /// <param name="childName">子对象</param>
    /// <typeparam name="T">泛型</typeparam>
    /// <returns></returns>
    public static T GetTheChildNodeComponentScripts<T>(GameObject goParent, string childName) where T : Component
    {
        Transform searchTransform = null;
        searchTransform = FindTheChildNode(goParent, childName);
        if (searchTransform != null)
        {
            return searchTransform.gameObject.GetComponent<T>();
        }
        else
        {
            return null;
        }
    }

    //给子节点添加脚本
    public static T AddChildNodeComponent<T>(GameObject goParent, string childName) where T : Component
    {
        Transform searchTransform = null;
        //查找特定子节点
        searchTransform = FindTheChildNode(goParent, childName);
        //如果查找成功，如果有相同的脚本时，则先删除，否则直接添加。
        if (searchTransform!=null)
        {
            T[] componentsScriptsArray = searchTransform.gameObject.GetComponents<T>();
            for (int i = 0; i < componentsScriptsArray.Length; i++)
            {
                if (componentsScriptsArray[i] != null)
                {
                    Destroy(componentsScriptsArray[i]);
                }
            }
            return searchTransform.gameObject.AddComponent<T>();
        }
        else
        {
            //如果查找不成功，返回Null。
            return null;
        }
       
    }
    
    //给子节点添加父对象
    public static void AddChildNodeToParentNode(Transform parents, Transform child)
    {
        child.SetParent(parents,false);
        child.localPosition = Vector3.zero;
        child.localScale = Vector3.one;
        child.localEulerAngles = Vector3.zero;
    }
}
